'''
Created on Jan 14, 2011

@author: Jonathan Herbst
'''

from boto.sqs.connection import SQSConnection
import time

class AWSAuthentication():
    
    _sQSConnection = None
    
    def __init__(self, accessKey, secretKey):
        self.m_accessKey = str(accessKey)
        self.m_secretKey = str(secretKey)
    
    def GetSQSConnection(self):
        if self._sQSConnection is None:
            self._sQSConnection = SQSConnection(self.m_accessKey, self.m_secretKey)
        return self._sQSConnection

class SQSReceiver():
    
    def __init__(self, queueName, aWSAuthentication):
        self.m_conn = aWSAuthentication.GetSQSConnection()
        self.m_queue = self.m_conn.get_queue(queueName)
        if self.m_queue is None:
            self.m_queue = self.m_conn.create_queue(queueName)
        
    def ReceiveMessages(self, messageBufferSize=10):
        """
        Method to receive all messages in the queue, acts as a generator function
        so calling context can manage memory
        
        Parameters:
            messageBufferSize - the size of the message buffer, in messages
            
        Yields:
            A message body string
        """
        
        def _GetMessages():
            return self.m_queue.get_messages(num_messages=messageBufferSize)
        
        # get next 10 messages from SQS
        messages = _GetMessages()
        
        while len(messages) > 0:
            
            # delete the messages from SQS immediately
            self._DeleteMessages(messages)
            
            # iterate through the messages
            for message in messages:
                #print self._ParseRawMessage(message)
                yield self._ParseRawMessage(message)
            
            # reset the message list
            messages = []
            
            if len(messages) >= messageBufferSize:
                # the max buffer size has been reached so there may be more
                # messages in the SQS queue
                messages = _GetMessages()
        
    
    def _ParseRawMessage(self, message):
        """
        Get the message content from a boto message object
        
        Parameters:
            message - a boto SQS message object
            
        Returns:
            the string of the message body
        """
        return str(message.get_body())
    
    def _DeleteMessages(self, messages):
        """
        Delete the specified messages from the SQS Queue
        
        Parameters:
            messages - list of boto SQS messages to delete
        """
        messages = list(messages)
        for message in messages:
            self.m_queue.delete_message(message)
